package com.sikaryofficial.gateway.config.properties;

import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import com.sikaryofficial.common.core.secure.SecureComponentFactory;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.Objects;

/**
 * API安全配置
 *
 * @author ruoyi
 */
@Slf4j
@Getter
@Setter
@ToString
@Configuration
@RefreshScope
@ConfigurationProperties(prefix = SecureProperties.SECURE_PROPERTIES_PREFIX)
public class SecureProperties {
    public static final String SECURE_PROPERTIES_PREFIX = "api.gateway.secure";

    public static final String RESPONSE_ENABLE = SECURE_PROPERTIES_PREFIX + ".response-switch.enable";

    /**
     * 算法
     */
    private SymmetricAlgorithm algorithm;

    /**
     * 响应开关
     */
    private SecureSwitch responseSwitch;
    /**
     * 待加密列表
     */
    private List<String> encryptUriList;
    /**
     * 不需要加密列表
     */
    private List<String> noEncryptUriList;

    public void checkSupportedAlgorithm() {
        log.info("校验是否支持算法：{}", algorithm);
        if (Objects.isNull(algorithm)) {
            return;
        }
        boolean supportedAlgorithm = SecureComponentFactory.isSupportedAlgorithm(algorithm);
        if (!supportedAlgorithm) {
            throw new UnsupportedOperationException("不支持的算法");
        }
        log.info("校验是否支持算法：校验通过");
    }

    /**
     * 是否启用加密响应参数
     *
     * @return 默认为否，其他情况看配置
     */
    public boolean enableEncryptResponseParam() {
        if (Objects.isNull(responseSwitch)) {
            return false;
        }
        return responseSwitch.getEnable();
    }
}
